require 'httparty'

module Pushnote
  class Note
    include HTTParty

    headers 'Content-Type' => 'application/json', 'Accept' => 'application/json'

    attr_accessor :title, :body
    attr_reader :top_report, :df_report, :git_status_report, :git_log_report, :git_diff_report

    def initialize
      set_server_host(configuration.server)
    end

    def save
      self.class.post('/', { body: serialize.to_json })
    end

    def set_server_host(host)
      self.class.base_uri(host)
    end

    def collect_system_info
      [
        Thread.new { create_top_report },
        Thread.new { create_df_report },
        Thread.new { create_git_status_report },
        Thread.new { create_git_log_report },
        Thread.new { create_git_diff_report }
      ].each(&:join)
    end

    private

    def serialize
      {
        title: title,
        body: body,
        snapshot: {
          top: top_report,
          df: df_report,
          git_status: git_status_report,
          git_log: git_log_report,
          git_diff: git_diff_report
        }
      }
    end

    def configuration
      @configuration ||= Configuration.new
    end

    def create_top_report
      @top_report ||= `top -l 1 -o +command -O pid`
    end

    def create_df_report
      @df_report ||= `df -h`
    end

    def create_git_status_report
      @git_status_report ||= `git status`
    end

    def create_git_log_report
      @git_log_report ||= `git log origin/master --pretty=oneline --abbrev-commit --decorate`
    end

    def create_git_diff_report
      @git_diff_report ||= `git diff`
    end
  end
end
